package com.kmzx.one.project.config.listener;

import com.kmzx.one.common.constants.Constants;
import com.kmzx.one.project.entity.UserOrder;
import com.kmzx.one.project.events.PayOrderEvent;
import com.kmzx.one.project.mapper.CustomerMapper;
import com.kmzx.one.project.mapper.UserInviteMapper;
import com.kmzx.one.project.mapper.UserOrderMapper;
import com.kmzx.one.project.mapper.WarehouseMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Component("payOrderListener")
public class PayOrderListener {

    private static Logger logger = LoggerFactory.getLogger(PayOrderListener.class);

    private static String expirePrefix = "expires_";

    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    UserOrderMapper userOrderMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    UserInviteMapper userInviteMapper;

    @Autowired
    WarehouseMapper warehouseMapper;

    @Async
    @EventListener(classes = {PayOrderEvent.class})
    @Transactional(rollbackFor = Exception.class)
    public void defaultPayOrderEvent(PayOrderEvent payOrderEvent) {
        logger.info("---------------------------");
        logger.info("利用@EventListener注解监听用户支付事件并向用户发送 收益");
        UserOrder order = payOrderEvent.getUserOrder();
        Date updateTime = new Date();
        order.setUpdateTime(updateTime);
        Integer states = order.getStates();
        // todo  交易成功
        if (states == 1) {
            //  todo 更新主订单表
            userOrderMapper.updateByIdSelective(order);
            // todo 更新子订单表
            userOrderMapper.batchUpdateSubOrder(order.getId(), 1, updateTime);
            // todo  更新库存表
            warehouseMapper.successWarehouseDetail(2,updateTime,order.getId());
            stringRedisTemplate.delete(Constants.lifestyleOrderPrefix + order.getId());
        }

        // todo  交易失败
        if (states == 5) {
            //  todo 更新主订单表
            userOrderMapper.updateByIdSelective(order);
            // todo 更新子订单表
            userOrderMapper.batchUpdateSubOrder(order.getId(), 5, updateTime);
        }

        stringRedisTemplate.delete(expirePrefix + order.getId());
    }


}


